<template>
  <div class="ewe-mating-view">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button type="primary" @click="handleAddNew" :icon="Plus">
          + 新增
        </el-button>
        <el-button type="success" @click="saveData" :icon="Document" :disabled="!isFormValid">
          保存
        </el-button>
        <el-button @click="handleUndo" :icon="RefreshLeft" :disabled="!hasChanges">
          撤销
        </el-button>
        <!-- <el-button type="danger" @click="handleDelete" :icon="Delete" :disabled="!isEditMode">
          删除
        </el-button> -->
      </div>
      <div class="action-right">
        <el-icon class="action-icon">
          <Setting />
        </el-icon>
        <el-icon class="action-icon">
          <Printer />
        </el-icon>
      </div>
    </div>

    <!-- 头部表单区域 -->
    <div class="form-section">
      <div class="form-row">
        <div class="form-item">
          <label class="required">负责人</label>
          <el-select v-model="formData.responsibleFor" placeholder="请选择">
            <el-option label="海绵宝宝" value="海绵宝宝" />
            <el-option label="派大星" value="派大星" />
            <el-option label="蟹老板" value="蟹老板" />
          </el-select>
        </div>
        <div class="form-item">
          <label class="required">配种日期</label>
          <el-date-picker v-model="formData.mainMatingTime" type="date" placeholder="选择日期" format="YYYY/MM/DD"
            value-format="YYYY/MM/DD" />
        </div>
        <div class="form-item">
          <label>单据号</label>
          <el-input v-model="formData.documentNumber" readonly />
        </div>
        <div class="form-item">
          <label>流水号</label>
          <el-input v-model="formData.serialNumber" readonly />
        </div>
      </div>
    </div>

    <!-- 主数据表格区域 -->
    <div class="table-section">
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="*耳号" width="120">
          <template #default="{ row, $index }">
            <el-input v-model="row.ewematingSnowId" placeholder="请输入耳号"
              @blur="validateRequiredField(row, 'ewematingSnowId', $index)" />
          </template>
        </el-table-column>
        <el-table-column label="*首配公羊" width="120">
          <template #default="{ row, $index }">
            <el-input v-model="row.ewematingFirstpair" placeholder="请输入首配公羊"
              @blur="validateRequiredField(row, 'ewematingFirstpair', $index)" />
          </template>
        </el-table-column>
        <el-table-column label="*配种方式" width="160">
          <template #default="{ row, $index }">
            <el-select v-model="row.ewematingMethod" placeholder="请选择"
              @change="validateRequiredField(row, 'ewematingMethod', $index)">
              <el-option label="鲜精-阴道" value="鲜精-阴道" />
              <el-option label="鲜精-子宫角" value="鲜精-子宫角" />
              <el-option label="冻精-阴道" value="冻精-阴道" />
              <el-option label="冻精-子宫角" value="冻精-子宫角" />
              <el-option label="模糊本交" value="模糊本交" />
              <el-option label="精准本交" value="精准本交" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="*种母发情类型" width="150">
          <template #default="{ row, $index }">
            <el-select v-model="row.ewematingEstrus" placeholder="请选择"
              @change="validateRequiredField(row, 'ewematingEstrus', $index)">
              <el-option label="自然交配" value="自然交配" />
              <el-option label="人工授精" value="人工授精" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="首配评分" width="110">
          <template #default="{ row }">
            <el-select v-model="row.ewematingRating" placeholder="请选择">
              <el-option label="1分" value="1" />
              <el-option label="2分" value="2" />
              <el-option label="3分" value="3" />
              <el-option label="4分" value="4" />
              <el-option label="5分" value="5" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="当前栋舍" width="150">
          <template #default="{ row }">
            <el-select v-model="row.ewePoultryhouse" placeholder="请选择">
              <el-option label="大羊舍" value="大羊舍" />
              <el-option label="配种舍" value="配种舍" />
              <el-option label="采购羊栋舍" value="采购羊栋舍" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="当前栏位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.ewematingField" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="转入栋舍" width="150">
          <template #default="{ row }">
            <el-select v-model="row.eweTransferhouse" placeholder="请选择">
              <el-option label="大羊舍" value="大羊舍" />
              <el-option label="配种舍" value="配种舍" />
              <el-option label="采购羊栋舍" value="采购羊栋舍" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="转入栏位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.ewematingTransfer" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="繁殖状态" width="130">
          <template #default="{ row }">
            <el-select v-model="row.reproductiveStatus" placeholder="请选择">
              <el-option label="已怀孕" :value="true" />
              <el-option label="未怀孕" :value="false" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="事件日期" width="180">
          <template #default="{ row }">
            <el-date-picker v-model="row.ewematingDateTime" type="date" placeholder="选择日期" format="YYYY/MM/DD"
              value-format="YYYY/MM/DD" />
          </template>
        </el-table-column>
        <el-table-column label="重量(公斤)" width="120">
          <template #default="{ row }">
            <el-input-number v-model="row.ewematingWeight" :min="0" :max="200" :precision="2" controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="备注" width="120">
          <template #default="{ row }">
            <el-input v-model="row.remarks" placeholder="请输入备注" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部操作和统计区域 -->
    <div class="footer-section">
      <div class="row-actions">
        <el-button type="primary" @click="handleAddRow" :icon="Plus">
          + 增行
        </el-button>
        <el-button type="danger" @click="handleDeleteRows" :icon="Delete">
          - 删行
        </el-button>
      </div>

      <div class="summary-section">
        <div class="summary-label">合计</div>
        <div class="totals-section">
          <div class="total-item">
            <span class="total-label">总重量:</span>
            <span class="total-value">{{ totalWeight.toFixed(2) }}kg</span>
          </div>
          <div class="total-item">
            <span class="total-label">总记录数:</span>
            <span class="total-value">{{ tableData.length }}</span>
          </div>
        </div>
      </div>

      <div class="remarks-section">
        <label>备注</label>
        <el-input v-model="formData.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Document,
  RefreshLeft,
  Delete,
  Setting,
  Printer
} from '@element-plus/icons-vue'
import { Writes, Reads } from '@/Utils/axiosHelper'
import { useRoute, useRouter } from 'vue-router'
//http://localhost:5008/api/Management/AddEwemating
// 接口类型定义
interface TableRow {
  "ewematingId"?: number, // 修改时需要这个字段
  "ewematingSnowId": string,
  "ewematingFirstpair": string,
  "ewematingMethod": string,
  "ewematingEstrus": string,
  "ewematingRating": string,
  "ewePoultryhouse": string,
  "ewematingField": string,
  "eweTransferhouse": string,
  "ewematingTransfer": string,
  "reproductiveStatus": boolean,
  "ewematingDateTime": string,
  "ewematingWeight": number,
  "remarks": string
}

// 响应式数据
const route = useRoute()
const router = useRouter()

const formData = reactive({
  responsibleFor: '',
  mainMatingTime: '',
  documentNumber: '',
  serialNumber: '',
  remarks: ''
})

const tableData = ref<TableRow[]>([])
const selectedRows = ref<TableRow[]>([])
const isEditMode = ref(false)
const originalData = ref<any>(null)

// 计算属性
const hasTableData = computed(() => tableData.value.length > 0)
const hasChanges = computed(() => {
  if (!originalData.value) return false
  return JSON.stringify(formData) !== JSON.stringify(originalData.value.formData) ||
    JSON.stringify(tableData.value) !== JSON.stringify(originalData.value.tableData)
})

const isFormValid = computed(() => {
  // 检查表单必填字段
  if (!formData.responsibleFor || !formData.mainMatingTime) return false

  // 检查是否有表格数据
  if (tableData.value.length === 0) return false

  // 检查表格数据必填字段
  return tableData.value.every(row =>
    row.ewematingSnowId &&
    row.ewematingFirstpair &&
    row.ewematingMethod &&
    row.ewematingEstrus
  )
})

const totalWeight = computed(() => {
  return tableData.value.reduce((sum, row) => sum + (row.ewematingWeight || 0), 0)
})
// 生成单据号和流水号
const generateDocumentNumbers = () => {
  const timestamp = Date.now()
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  // 单据号格式：PC + 年月日 + 时间戳后6位
  formData.documentNumber = `PC${year}${month}${day}${String(timestamp).slice(-6)}`

  // 流水号格式：SN + 时间戳
  formData.serialNumber = `SN${timestamp}`
}
// 添加新行
const addNewRow = () => {
  const newRow: TableRow = {
    "ewematingSnowId": "",
    "ewematingFirstpair": "",
    "ewematingMethod": "",
    "ewematingEstrus": "",
    "ewematingRating": "",
    "ewePoultryhouse": "",
    "ewematingField": "",
    "eweTransferhouse": "",
    "ewematingTransfer": "",
    "reproductiveStatus": true,
    "ewematingDateTime": "2025-10-20T03:04:27.156Z",
    "ewematingWeight": 0,
    "remarks": ""
  }
  tableData.value.push(newRow)
  saveOriginalData()
}

// 删除行
const deleteSelectedRows = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行')
    return
  }

  const selectedIds = selectedRows.value.map(row => tableData.value.indexOf(row))
  tableData.value = tableData.value.filter((_, index) => !selectedIds.includes(index))
  selectedRows.value = []
  saveOriginalData()
  ElMessage.success(`已删除 ${selectedIds.length} 行数据`)
}

// 顶部操作栏方法
const handleAddNew = () => {
  ElMessageBox.confirm('确定要新增记录吗？当前未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    resetForm()
    ElMessage.success('已重置表单')
  }).catch(() => {
    // 用户取消
  })
}

// 保存数据到后端
const saveData = async () => {
  try {
    // 校验表单必填字段
    if (!formData.responsibleFor) {
      ElMessage.warning('请选择负责人');
      return;
    }

    if (!formData.mainMatingTime) {
      ElMessage.warning('请选择配种日期');
      return;
    }

    // 校验表格数据
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('请至少添加一条配种记录');
      return;
    }

    // 过滤并校验有效数据
    const validRows = tableData.value.filter(row =>
      row.ewematingSnowId &&
      row.ewematingFirstpair &&
      row.ewematingMethod &&
      row.ewematingEstrus
    );

    if (validRows.length === 0) {
      ElMessage.warning('请至少填写一条完整的数据（耳号、首配公羊、配种方式、种母发情类型）');
      return;
    }

    // 数据已通过validRows过滤并验证，直接使用

    // 处理新增数据的请求体格式（根据 Swagger 图片）
    if (validRows.filter(row => !row.ewematingId).length > 0) {
      const addPayload = {
        ewematingList: validRows.filter(row => !row.ewematingId).map(row => {
          // 转换日期格式：从 YYYY/MM/DD 转换为 ISO 格式
          let formattedDateTime = row.ewematingDateTime;
          if (formattedDateTime && formattedDateTime.includes('/')) {
            // 将 YYYY/MM/DD 转换为 YYYY-MM-DD
            formattedDateTime = formattedDateTime.replace(/\//g, '-');
            // 如果没有时间部分，添加默认时间
            if (!formattedDateTime.includes('T')) {
              formattedDateTime = `${formattedDateTime}T00:00:00`;
            }
          }

          return {
            ewematingSnowId: row.ewematingSnowId,
            ewematingFirstpair: row.ewematingFirstpair,
            ewematingMethod: row.ewematingMethod,
            ewematingEstrus: row.ewematingEstrus,
            ewematingRating: row.ewematingRating,
            ewePoultryhouse: row.ewePoultryhouse,
            ewematingField: row.ewematingField,
            eweTransferhouse: row.eweTransferhouse,
            ewematingTransfer: row.ewematingTransfer,
            reproductiveStatus: row.reproductiveStatus,
            ewematingDatetime: formattedDateTime,
            ewematingWeight: row.ewematingWeight,
            remarks: row.remarks || ""
          }
        })
      };

      try {
        console.log('批量添加请求数据:', addPayload);
        const addRes = await Writes.post("Management/AddEwemating", addPayload);
        console.log('批量添加响应:', addRes);
        if (addRes.data.code == 100) {
          ElMessage.success(`批量添加成功，共添加${validRows.filter(row => !row.ewematingId).length}条记录`);
          router.push('/EwematingList');
          // 添加成功后，更新表格中的数据为编辑模式
          validRows.filter(row => !row.ewematingId).forEach(row => {
            row.ewematingId = Date.now(); // 临时ID，实际应该从响应中获取
          });
        } else {
          ElMessage.error(addRes.data.msg || '批量添加失败');
        }
      } catch (error: any) {
        console.error('批量添加失败', error);
        console.error('错误详情:', error.response?.data);
        ElMessage.error(error.response?.data?.msg || '批量添加失败');
      }
    }

    // 处理修改数据的请求体格式（根据 Swagger 图片）


    // 如果既有新增又有修改，显示总结消息
    const actualNewCount = validRows.filter(row => !row.ewematingId).length;
    const actualUpdateCount = validRows.filter(row => row.ewematingId).length;

    if (actualNewCount > 0 && actualUpdateCount > 0) {
      ElMessage.success(`保存完成！新增${actualNewCount}条，修改${actualUpdateCount}条`);
    } else if (actualNewCount > 0) {
      ElMessage.success(`保存完成！共新增${actualNewCount}条记录`);
    } else if (actualUpdateCount > 0) {
      ElMessage.success(`保存完成！共修改${actualUpdateCount}条记录`);
    }

    // 保存成功后，更新原始数据以支持撤销功能
    saveOriginalData();
  } catch (error) {
    console.error('保存失败', error);
    ElMessage.error('保存过程中发生错误');
  }
};

const handleUndo = () => {
  if (originalData.value) {
    Object.assign(formData, originalData.value.formData)
    tableData.value = [...(originalData.value.tableData || [])]
    ElMessage.success('已撤销更改')
  }
}

// 表格操作方法
const handleAddRow = () => {
  addNewRow()
}

const handleDeleteRows = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('没有可删除的行')
    return
  }

  if (selectedRows.value.length > 0) {
    deleteSelectedRows()
  } else {
    // 如果没有选择行，默认删除最后一行
    tableData.value.pop()
    saveOriginalData()
    ElMessage.success('已删除最后一行')
  }
}

const handleSelectionChange = (selection: TableRow[]) => {
  selectedRows.value = selection || []
}

const validateRequiredField = (row: TableRow, field: keyof TableRow, index: number) => {
  if (!row[field]) {
    ElMessage.warning(`第 ${index + 1} 行${getFieldLabel(field)}不能为空`)
    return false
  }
  return true
}

/**
 * 根据字段键获取对应的中文标签
 * 
 * @param field - 表格行的字段键
 * @returns 对应的中文标签，如果未定义则返回原字段键
 */
const getFieldLabel = (field: keyof TableRow): string => {
  const labels: { [key: string]: string } = {
    ewematingSnowId: '耳号',
    ewematingFirstpair: '首配公羊',
    ewematingMethod: '配种方式',
    ewematingEstrus: '种母发情类型'
  }
  return labels[field] || field
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    responsibleFor: '',
    mainMatingTime: '',
    documentNumber: '',
    serialNumber: '',
    remarks: ''
  })
  generateDocumentNumbers()
  tableData.value = []
  selectedRows.value = []
  isEditMode.value = false
  originalData.value = null
  // 初始化一行数据
  addNewRow()
}
onMounted(() => {
  generateDocumentNumbers()
})
// 保存原始数据（用于撤销功能）
const saveOriginalData = () => {
  originalData.value = {
    formData: { ...formData },
    tableData: JSON.parse(JSON.stringify(tableData.value))
  }
}


</script>

<style scoped>
.ewe-mating-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 15px 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.action-left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.action-right {
  display: flex;
  gap: 15px;
  align-items: center;
}

.action-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
  padding: 5px;
}

.action-icon:hover {
  color: #409eff;
}

/* 表单区域 */
.form-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  align-items: end;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-item label.required::after {
  content: ' *';
  color: #f56c6c;
}

.form-item :deep(.el-input),
.form-item :deep(.el-select),
.form-item :deep(.el-date-editor) {
  width: 100%;
}

/* 表格区域 */
.table-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 底部区域 */
.footer-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.row-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 20px;
}

.summary-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.summary-label {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.totals-section {
  display: flex;
  gap: 30px;
}

.total-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.total-label {
  font-weight: 500;
  color: #666;
  font-size: 14px;
}

.total-value {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.remarks-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.remarks-section label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.remarks-section :deep(.el-textarea) {
  width: 100%;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table td) {
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

:deep(.el-date-editor) {
  width: 100%;
}

/* 表格行样式 */
:deep(.el-table .el-table__row) {
  height: 45px;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f8f9fa;
}

/* 表格单元格样式 */
:deep(.el-table .el-table__cell) {
  padding: 0 8px;
}

/* 按钮样式优化 */
.action-left :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
}

.row-actions :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 8px 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .form-row {
    grid-template-columns: repeat(2, 1fr);
  }

  .totals-section {
    flex-wrap: wrap;
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }

  .action-left {
    flex-wrap: wrap;
    gap: 8px;
  }

  .action-right {
    gap: 10px;
  }

  .ewe-mating-view {
    padding: 10px;
  }

  .action-bar,
  .form-section,
  .table-section,
  .footer-section {
    margin-bottom: 15px;
  }

  .summary-section {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .totals-section {
    flex-direction: column;
    gap: 10px;
  }
}

/* 禁用状态样式 */
:deep(.el-button.is-disabled) {
  opacity: 0.5;
}
</style>